import pygame as pg

pg.init()

# 创建一个窗口
window = pg.display.set_mode((640, 360))
# 设置窗口标题
pg.display.set_caption("小鱼大作战")

sea = pg.image.load('pygame教程\Resource\images\sea.png')
fish_images = []
# 依次加载fish1.png, fish2.png, fish3.png
for i in range(1, 4):
        fish_img = pg.image.load(f'pygame教程/Resource/images/fish{i}.png')
        fish_images.append(fish_img)
# 创建鱼的左向版本（水平翻转）
fish_left_images = [pg.transform.flip(img, True, False) for img in fish_images]

current_direction = 'right'
current_fish_index = 0
fish_rect = fish_images[0].get_rect()
fish_rect.center = window.get_rect().center

# 动画控制
animation_speed = 20  # 每20帧切换一次图片
frame_count = 0

clock = pg.time.Clock()

isRunning = True
while isRunning:
    # 处理事件
    for ev in pg.event.get():  # 取出并返回所有待处理的事件
        # 退出事件
        if ev.type == pg.QUIT:
            isRunning = False
            break
        
    keys = pg.key.get_pressed()
    if keys[pg.K_UP]:
        fish_rect.y -= 1
    if keys[pg.K_DOWN]:
        fish_rect.y += 1
    if keys[pg.K_LEFT]:
        current_direction = 'left'
        fish_rect.x -= 1
    if keys[pg.K_RIGHT]:
        current_direction = 'right'
        fish_rect.x += 1

    # 更新动画帧
    frame_count += 1
    if frame_count >= animation_speed:
        frame_count = 0
        current_fish_index = (current_fish_index + 1) % len(fish_images)

    # 根据方向选择正确的图片
    if current_direction == "right":
        current_fish = fish_images[current_fish_index]
    else:
        current_fish = fish_left_images[current_fish_index]

    window.blit(sea, (0, 0))
    window.blit(current_fish, fish_rect)

    pg.display.update()
    clock.tick(120)

pg.quit()